package com.dragon.mmochat.service;

import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dragon.mmochat.MmochatConstant;
import com.dragon.mmochat.MmochatMain;
import com.dragon.mmochat.message.Mmochat_18_1C;
import com.dragon.mmochat.message.Mmochat_18_2S;
import com.dragon.mmochat.message.Mmochat_18_3C;
import com.dragon.mmochat.message.Mmochat_18_4C;
import com.dragon.mmochat.message.Mmochat_18_5C;
import com.dragon.mmochat.message.Mmochat_18_6C;
import com.dragon.mmochat.message.Mmochat_18_7C;
import com.dragon.mmochat.message.Mmochat_18_8C;
import com.dragon.mmochat.model.deal.MmochatBigMoneyDeal;
import com.dragon.mmochat.model.enumType.MmochatBigMoneyDealState;
import com.dragon.mmochat.model.enumType.MmochatBigMoneyDealType;
import com.dragon.mmochat.model.gang.MmochatGang;
import com.dragon.mmochat.model.mergeServer.MergeServer;
import com.dragon.mmochat.model.role.MmochatPlayer;
import com.dragon.mmochat.util.MmochatUtil;
import com.skymobi.handler.SkymobiHandler;
import com.skymobi.message.SkymobiProtocolMessage;
import com.skymobi.service.SkymobiService;

//元宝交易服务
public class MmochatBigMoneyDealService {
	private static Logger log = LoggerFactory
			.getLogger(MmochatBattleService.class);
	public static ScheduledExecutorService checkOrderTimeOutThread = Executors
			.newScheduledThreadPool(1);

	public static final int maxSizePerPageOfBigMoneyDeal = 12;

	// 进行中的元宝交易订单
	public static Map<Integer, MmochatBigMoneyDeal> dealMap = new ConcurrentHashMap<Integer, MmochatBigMoneyDeal>();

	public void init() {
		try {
			// 从数据库加载所有未结束的订单交易
			List<MmochatBigMoneyDeal> unclosedDealList = MmochatDao
					.getAllUnclosedDeal();
			System.out.println("元宝订单加载完成");
			for (MmochatBigMoneyDeal deal : unclosedDealList) {
				if (!deal.isValid()) {
					// 维护期间已经过期，延长一定的时间(1小时内)
					long newLifeTime = (long) (Math.random() * MmochatConstant.MS_PER_HOUR);
					deal.setStartTick(System.currentTimeMillis()
							- MmochatConstant.bigmoneyDealOrderLifeTime
							+ newLifeTime);
				}
				dealMap.put(deal.getId(), deal);
			}
			unclosedDealList.clear();
			if (MmochatMain.openMergeServer) {
				if (MmochatMain.mergeServerStep == 1) {
					// 合服才能用
					MergeServer server = new MergeServer();
					server.run();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 检查订单是否过期
		checkOrderTimeOutThread.scheduleWithFixedDelay(new checkOrderTimeOut(),
				60, 60, TimeUnit.SECONDS);

	}

	class checkOrderTimeOut implements Runnable {
		@Override
		public void run() {
			try {
				List<MmochatBigMoneyDeal> dealNeedUpdate = new ArrayList<MmochatBigMoneyDeal>();
				for (MmochatBigMoneyDeal deal : dealMap.values()) {
					try {
						if (deal != null) {
							synchronized (deal) {
								if (!deal.isValid()) {
									// 已过期：更新订单状态,将订单里的金钱/元宝转入发布者的账户中
									if (deal.getState() == MmochatBigMoneyDealState.交易中) {
										deal
												.setState(MmochatBigMoneyDealState.交易结束);
										dealNeedUpdate.add(deal);
									}
								}
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				try {
					MmochatDao
							.batchUpdateAfterBigMoneyDealTimeOut(dealNeedUpdate);
					// 更新内存
					try {
						for (MmochatBigMoneyDeal deal : dealNeedUpdate) {
							dealMap.remove(deal.getId());
							MmochatPlayer me = MmochatMainService
									.getRoleFromBuffer(deal.getRoleId());
							if (me == null) {
								continue;
							}
							if (deal.getType() == MmochatBigMoneyDealType.寄售) {
								// 归还剩余元宝
								me.addAccount_bigmoney(deal.getRest());
							} else if (deal.getType() == MmochatBigMoneyDealType.求购) {
								// 归还剩余金钱
								me.addAccount_smallmoney(deal.getRest()
										* deal.getPrice() * 100);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} catch (Exception e) {
					e.printStackTrace();
					// 恢复状态
					for (MmochatBigMoneyDeal deal : dealNeedUpdate) {
						deal.setState(MmochatBigMoneyDealState.交易中);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// 删除所有此订单的roleId，不归还金钱元宝
	public static void delOrdersByRoleId(int roleId) {
		try {
			List<MmochatBigMoneyDeal> dealNeedUpdate = new ArrayList<MmochatBigMoneyDeal>();
			for (MmochatBigMoneyDeal deal : dealMap.values()) {
				try {
					if (deal != null && deal.getRoleId() == roleId) {
						deal.setState(MmochatBigMoneyDealState.交易结束);
						dealNeedUpdate.add(deal);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			try {
				MmochatDao.batchDeleteBigMoneyDeal(dealNeedUpdate);
				// 更新内存
				try {
					for (MmochatBigMoneyDeal deal : dealNeedUpdate) {
						dealMap.remove(deal.getId());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				e.printStackTrace();
				// 恢复状态
				for (MmochatBigMoneyDeal deal : dealNeedUpdate) {
					deal.setState(MmochatBigMoneyDealState.交易中);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 获取所有的交易列表，并按时间排序
	public static List<MmochatBigMoneyDeal> getOrderListByType(
			MmochatBigMoneyDealType type) {
		List<MmochatBigMoneyDeal> list = new ArrayList<MmochatBigMoneyDeal>();
		for (MmochatBigMoneyDeal deal : dealMap.values()) {
			if (deal.getType() == type) {
				list.add(deal);
			}
		}
		Collections.sort(list);
		return list;
	}

	// 获取指定玩家的交易列表,并按时间排序
	public static List<MmochatBigMoneyDeal> getOrderListByRoleId(int roleId) {
		List<MmochatBigMoneyDeal> list = new ArrayList<MmochatBigMoneyDeal>();
		for (MmochatBigMoneyDeal deal : dealMap.values()) {
			if (deal.getRoleId() == roleId) {
				list.add(deal);
			}
		}
		Collections.sort(list);
		return list;
	}

	// 创建订单
	@SkymobiService
	public SkymobiProtocolMessage handleC_18_1(SkymobiHandler handler,
			Mmochat_18_1C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		// 检查是否有足够的金钱或元宝
		String info;
		synchronized (me) {
			// 查询此玩家已有的订单
			int count = 0;
			for (MmochatBigMoneyDeal deal : dealMap.values()) {
				if (deal.getRoleId() == me.getRoleId()) {
					count++;
				}
			}
			if (count >= MmochatConstant.maxBigMoneyDealOrderNumPerRole) {
				return MmochatUtil.msgbox(req.getHallState(), "您当前已经发布了"
						+ count + "个未完结的订单，不能再发布了!");
			}
			MmochatBigMoneyDealType dealType = MmochatBigMoneyDealType.get(req
					.getOrderType());
			if (dealType == null) {
				return MmochatUtil.msgbox(req.getHallState(),
						"未知的订单类型，发布失败!请联系客服解决。订单类型:" + req.getOrderType());
			}
			if (req.getPrice() <= 0 || req.getAmount() <= 0) {
				return MmochatUtil.msgbox(req.getHallState(), "请输入大于0的数字!");
			}

			info = "";
			int addSmallMoney = 0, addBigMoney = 0;
			switch (dealType) {
			case 求购: {
				if (req.getPrice() > MmochatConstant.maxBigMoneyDealBuyOrderPrice) {
					return MmochatUtil
							.msgbox(
									req.getHallState(),
									"求购订单单价最大不能超过"
											+ MmochatConstant.maxBigMoneyDealBuyOrderPrice
											+ "万文/100元宝!");
				}
				if (me.getLevel() < MmochatConstant.minBigMoneyDealBuyOrderLevelNeed
						&& me.getDao() < MmochatConstant.minBigMoneyDealBuyOrderDaoNeed) {
					return MmochatUtil
							.msgbox(
									req.getHallState(),
									"发布求购订单要求人物达到"
											+ MmochatConstant.minBigMoneyDealBuyOrderLevelNeed
											+ "级，或者道行达到"
											+ MmochatUtil
													.getDaoSimpleString(MmochatConstant.minBigMoneyDealBuyOrderDaoNeed)
											+ "，您两者都不符合，无法发布求购订单。");
				}
				long smallMoneyNeed = 1L * req.getPrice()
						* (req.getAmount() / 100) * 10000;
				if (smallMoneyNeed <= 0
						|| smallMoneyNeed > (long) Integer.MAX_VALUE) {
					return MmochatUtil
							.msgbox(req.getHallState(), "您输入的数字超过上限!");
				}
				if ((long) me.getSmall_money() < smallMoneyNeed) {
					return MmochatUtil.msgbox(req.getHallState(), "求购"
							+ req.getAmount() + "元宝(" + req.getPrice()
							+ "万文/100元宝)一共需要"
							+ MmochatUtil.getColorMoney(smallMoneyNeed)
							+ "文钱,您的包裹里只有"
							+ MmochatUtil.getColorMoney(me.getSmall_money())
							+ "文钱。");
				}
				addSmallMoney = (int) (-1 * smallMoneyNeed);
				info += "订单发布成功!您可以到<我的账户>查看订单交易情况。"
						+ MmochatUtil.wrapColor(
								"如果交易成功，求购到的元宝将暂时保存到<我的账户>中，请从<我的账户>中取回元宝!",
								Color.yellow)
						+ MmochatUtil.wrapColor("元宝交易平台获得的元宝，无法再次在此平台寄售!",
								Color.red);
				break;
			}
			case 寄售: {
				if (req.getPrice() > MmochatConstant.maxBigMoneyDealSellOrderPrice) {
					return MmochatUtil
							.msgbox(
									req.getHallState(),
									"求购订单单价最大不能超过"
											+ MmochatConstant.maxBigMoneyDealSellOrderPrice
											+ "万文/100元宝!");
				}
				if (req.getAmount() <= 0) {
					return MmochatUtil.msgbox(req.getHallState(), "元宝数量必需大于0!");
				}
				if (me.getBig_money() < req.getAmount()) {
					return MmochatUtil.msgbox(req.getHallState(), "您的元宝不足"
							+ req.getAmount() + ",您当前只有" + me.getBig_money()
							+ "元宝,请先充值。订单发布失败!");
				}
				if (me.getBig_money() - me.getLimit_bigmoney() < req
						.getAmount()) {
					String msg = "您的可寄售元宝不足" + req.getAmount() + ",您当前有"
							+ me.getBig_money() + "元宝,其中"
							+ me.getLimit_bigmoney() + "元宝是通过交易平台购买的,无法再次寄售。";
					if (me.getAccount_bigmoney() > 0) {
						msg += "您的元宝交易账户中还有" + me.getAccount_bigmoney()
								+ "元宝未取回!";
					}

					return MmochatUtil.msgbox(req.getHallState(), msg);
				}
				addBigMoney = -1 * req.getAmount();
				info += "订单发布成功!您可以到<我的账户>查看订单交易情况。"
						+ MmochatUtil.wrapColor(
								"如果交易成功，出售所得金钱将暂时保存到<我的账户>中，请从<我的账户>中取回金钱!",
								Color.yellow);
				break;
			}
			default:
				break;
			}
			// 发布订单
			MmochatBigMoneyDeal newDeal = new MmochatBigMoneyDeal();
			newDeal.setType(dealType);
			newDeal.setState(MmochatBigMoneyDealState.交易中);
			newDeal.setPrice(req.getPrice());
			newDeal.setAmount(req.getAmount());
			newDeal.setRest(req.getAmount());
			newDeal.setRoleId(me.getRoleId());
			newDeal.setStartTick(System.currentTimeMillis());
			try {
				MmochatDao.createBigMoneyDealOrder(newDeal, addSmallMoney,
						addBigMoney);
			} catch (Exception e) {
				e.printStackTrace();
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}
			if (addSmallMoney != 0) {
				me.addAndUpdateSmall_money(addSmallMoney);
			}
			if (addBigMoney != 0) {
				me.addBig_money(addBigMoney);
			}
			dealMap.put(newDeal.getId(), newDeal);
		}
		sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
		return MmochatUtil.msgbox(req.getHallState(), info);
	}

	// 18.3 购买元宝
	@SkymobiService
	public SkymobiProtocolMessage handleC_18_3(SkymobiHandler handler,
			Mmochat_18_3C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		int num = req.getNum();
		if (num < 100 || num % 100 != 0) {
			sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
			return MmochatUtil.msgbox(req.getHallState(), "购买的元宝数量必须是100的倍数!");
		}
		MmochatBigMoneyDeal deal = dealMap.get(req.getDealId());
		if (deal == null) {
			// 刷新列表
			sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
			return MmochatUtil.msgbox(req.getHallState(), "此订单已经交易结束,无法购买!");
		}
		synchronized (deal) {
			// 检查订单状态
			if (deal == null
					|| deal.getState() == MmochatBigMoneyDealState.交易结束
					|| deal.getRest() == 0) {
				// 刷新列表
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil
						.msgbox(req.getHallState(), "此订单已经交易结束,无法购买!");
			}
			// 检查玩家金钱是否足够
			long moneyNeedL = 10000L * deal.getPrice() * num / 100;
			if (moneyNeedL > Integer.MAX_VALUE) {
				return MmochatUtil.msgbox(req.getHallState(), "此订单交易超出限额!");
			}
			if (moneyNeedL < 0) {
				return MmochatUtil.msgbox(req.getHallState(), "此订单交易超出限额!");
			}
			if ((long) me.getSmall_money() < moneyNeedL) {
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "您的金钱不足"
						+ MmochatUtil.getColorMoney(moneyNeedL) + "文!");
			}
			int moneyNeed = (int) moneyNeedL;
			// 检查订单元宝是否足够
			if (deal.getRest() < num) {
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "此订单剩余元宝量已不足"
						+ num + ",请重新购买!");
			}

			// 订单中扣除元宝、 如果订单已售尽，则修改状态并删除订单，增加购买人
			deal.delRest(num);
			if (deal.isOver()) {
				deal.setState(MmochatBigMoneyDealState.交易结束);
			}
			Integer dealCount = deal.getDealerMap().get(me.getRoleId());
			if (dealCount == null) {
				deal.getDealerMap().put(me.getRoleId(), num);
			} else {
				dealCount += num;
				deal.getDealerMap().put(me.getRoleId(), dealCount);
			}

			// 操作数据库:更新订单，给购买者增加元宝和扣除金钱，给出售者的金钱账户增加金钱
			long oldLimitBigmoney = me.getLimit_bigmoney();
			me.addLimit_bigmoney(num);
			MmochatPlayer seller = MmochatGmService.getRoleInfoById(deal
					.getRoleId());
			long sellerLimit = 0;
			if (seller != null) {
				sellerLimit = seller.getLimit_bigmoney();
			}
			try {
				MmochatDao.buyBigMoneyDeal(deal, num, num, -1 * moneyNeed, 0,
						0, me.getLimit_bigmoney(), me.getRoleId(), 0, 0, 0,
						moneyNeed, sellerLimit, deal.getRoleId());
			} catch (Exception e) {
				e.printStackTrace();
				me.setLimit_bigmoney(oldLimitBigmoney);
				deal.delRest(-1 * num);
				if (!deal.isOver()) {
					deal.setState(MmochatBigMoneyDealState.交易中);
				}
				dealCount = deal.getDealerMap().get(me.getRoleId());
				if (dealCount != null) {
					dealCount -= num;
					if (dealCount <= 0) {
						deal.getDealerMap().remove(me.getRoleId());
					} else {
						deal.getDealerMap().put(me.getRoleId(), dealCount);
					}
				}
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}

			// 内存操作：玩家增加元宝，扣除金钱，增加限制交易元宝数量，出售玩家的金钱账户增加金钱；
			me.addBig_money(num);
			me.addAndUpdateSmall_money(-1 * moneyNeed);

			if (seller != null) {
				seller.addAccount_smallmoney(moneyNeed);
				MmochatFriendService.sendSystemMsgToPersonByFriendMessage(
						seller, "您出售的元宝被人买走了"
								+ num
								+ "个,"
								+ MmochatUtil.getColorMoney(moneyNeed)
								+ "文钱已经转入您的账户,请按9键进入"
								+ MmochatUtil.wrapColor("元宝交易-我的账户",
										Color.magenta) + ",取出售得的金钱。");
			}

			if (deal.isOver()) {
				dealMap.remove(deal.getId());
			}
		}
		// 下发刷新列表
		sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
		return MmochatUtil.msgbox(req.getHallState(), "购买成功!您获得了"
				+ MmochatUtil.wrapColor(num + "元宝!", Color.yellow)
				+ MmochatUtil.wrapColor("元宝交易平台购买的元宝，无法在此平台再次寄售。", Color.red)
				+ "您当前共有" + me.getBig_money() + "元宝，其中有"
				+ me.getLimit_bigmoney() + "元宝限制寄售。");
	}

	// 18.4 出售元宝
	@SkymobiService
	public SkymobiProtocolMessage handleC_18_4(SkymobiHandler handler,
			Mmochat_18_4C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}

		int num = req.getNum();
		if (num < 100 || num % 100 != 0) {
			sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
			return MmochatUtil.msgbox(req.getHallState(), "出售的元宝数量必须是100的倍数!");
		}
		MmochatBigMoneyDeal deal = dealMap.get(req.getDealId());
		long smallMoney = 0;
		if (deal == null) {
			sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
			return MmochatUtil.msgbox(req.getHallState(), "此订单已经交易结束!");
		}
		synchronized (deal) {
			// 检查订单状态
			if (deal == null
					|| deal.getState() == MmochatBigMoneyDealState.交易结束
					|| deal.getRest() == 0) {
				// 刷新列表
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "此订单已经交易结束!");
			}
			// 检查订单需要的元宝数
			if (deal.getRest() < num) {
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "此订单求购元宝量当前为"
						+ deal.getRest() + "元宝,不足" + num + "元宝,请重新下单!");
			}

			// 检查玩家元宝是否足够
			if (me.getBig_money() < num) {
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "您的元宝不足" + num
						+ "!");
			}
			smallMoney = 10000L * num * deal.getPrice() / 100;
			if (smallMoney > Integer.MAX_VALUE || smallMoney <= 0) {
				return MmochatUtil.msgbox(req.getHallState(), "交易数额非法!");
			}
			// 检查玩家包裹金钱上限
			if ((long) Integer.MAX_VALUE - me.getSmall_money() < smallMoney) {
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(),
						"您包裹里携带的金钱数过多，无法继续出售元宝!");
			}

			// 订单中扣除元宝、 如果订单已售尽，则修改状态并删除订单，增加购买人
			deal.delRest(num);
			if (deal.isOver()) {
				deal.setState(MmochatBigMoneyDealState.交易结束);
			}
			Integer dealCount = deal.getDealerMap().get(me.getRoleId());
			if (dealCount == null) {
				deal.getDealerMap().put(me.getRoleId(), num);
			} else {
				dealCount += num;
				deal.getDealerMap().put(me.getRoleId(), dealCount);
			}

			// 操作数据库:更新订单，给购买者增加元宝和扣除金钱，给出售者的金钱账户增加金钱
			MmochatPlayer seller = null;
			seller = MmochatGmService.getRoleInfoById(deal.getRoleId());
			long dealerLimit = 0;
			if (seller != null) {
				dealerLimit = seller.getLimit_bigmoney() + num;
			}
			try {
				MmochatDao.buyBigMoneyDeal(deal, num, -1 * num,
						(int) smallMoney, 0, 0, me.getLimit_bigmoney(), me
								.getRoleId(), 0, 0, num, 0, dealerLimit, deal
								.getRoleId());
			} catch (Exception e) {
				e.printStackTrace();
				deal.delRest(-1 * num);
				if (!deal.isOver()) {
					deal.setState(MmochatBigMoneyDealState.交易中);
				}
				dealCount = deal.getDealerMap().get(me.getRoleId());
				if (dealCount != null) {
					dealCount -= num;
					if (dealCount <= 0) {
						deal.getDealerMap().remove(me.getRoleId());
					} else {
						deal.getDealerMap().put(me.getRoleId(), dealCount);
					}
				}
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}

			// 内存操作：玩家扣除元宝，增加金钱，出售玩家的元宝账户增加元宝；
			me.addBig_money(-1 * num);
			me.addAndUpdateSmall_money((int) smallMoney);

			if (seller != null) {
				seller.addAccount_bigmoney(num);
				seller.addLimit_bigmoney(num);
				MmochatFriendService.sendSystemMsgToPersonByFriendMessage(
						seller, "您求购的元宝订单有"
								+ num
								+ "元宝已经购得,"
								+ "请按9键进入"
								+ MmochatUtil.wrapColor("元宝交易-我的账户",
										Color.magenta) + ",取出购得的元宝。");
			}

			if (deal.isOver()) {
				dealMap.remove(deal.getId());
			}
		}
		// 下发刷新列表
		sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
		return MmochatUtil
				.msgbox(req.getHallState(), "出售成功!"
						+ MmochatUtil.getColorMoney(smallMoney)
						+ MmochatUtil.wrapColor("文钱已经发放到您的包裹中，请按3键查询余额。",
								Color.yellow));
	}

	public static void sendBigMoneyDealWnd2Person(MmochatPlayer me,
			int hallState, int sellPageNo, int buyPageNo) {
		List<MmochatBigMoneyDeal> sellList = MmochatBigMoneyDealService
				.getOrderListByType(MmochatBigMoneyDealType.寄售);
		List<MmochatBigMoneyDeal> buyList = MmochatBigMoneyDealService
				.getOrderListByType(MmochatBigMoneyDealType.求购);
		List<MmochatBigMoneyDeal> myList = MmochatBigMoneyDealService
				.getOrderListByRoleId(me.getRoleId());

		int sellListPageNum = (sellList.size() + maxSizePerPageOfBigMoneyDeal - 1)
				/ maxSizePerPageOfBigMoneyDeal;
		sellListPageNum = Math.max(1, sellListPageNum);
		sellPageNo = Math.min(sellPageNo, sellListPageNum - 1);
		sellPageNo = Math.max(0, sellPageNo);
		int sellListStartIndex = sellPageNo * maxSizePerPageOfBigMoneyDeal;
		int sellListEndIndex = Math.min(sellListStartIndex
				+ maxSizePerPageOfBigMoneyDeal, sellList.size());

		int buyListPageNum = (buyList.size() + maxSizePerPageOfBigMoneyDeal - 1)
				/ maxSizePerPageOfBigMoneyDeal;
		buyListPageNum = Math.max(1, buyListPageNum);
		buyPageNo = Math.min(buyPageNo, buyListPageNum - 1);
		buyPageNo = Math.max(0, buyPageNo);
		int buyListStartIndex = buyPageNo * maxSizePerPageOfBigMoneyDeal;
		int buyListEndIndex = Math.min(buyListStartIndex
				+ maxSizePerPageOfBigMoneyDeal, buyList.size());

		Mmochat_18_2S pack = new Mmochat_18_2S();
		pack.setHallState(hallState);
		pack.setMe(me);
		pack.setSellPageNo(sellPageNo);
		pack.setTotalSellPageNum(sellListPageNum);
		pack.setBuyPageNo(buyPageNo);
		pack.setTotalBuyPageNum(buyListPageNum);
		pack.setSellOrderList(sellList.subList(sellListStartIndex,
				sellListEndIndex));
		pack.setBuyOrderList(buyList
				.subList(buyListStartIndex, buyListEndIndex));
		pack.setMyOrderList(myList);

		MmochatUtil.sendCommonPack(me, pack);
	}

	// 18.5 查看指定页的元宝交易界面
	@SkymobiService
	public SkymobiProtocolMessage handleC_18_5(SkymobiHandler handler,
			Mmochat_18_5C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		sendBigMoneyDealWnd2Person(me, req.getHallState(), req
				.getSellListPageNo(), req.getBuyListPageNo());
		return null;
	}

	// 18.6 取回元宝
	@SkymobiService
	public SkymobiProtocolMessage handleC_18_6(SkymobiHandler handler,
			Mmochat_18_6C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (me.getAccount_bigmoney() <= 0) {
			return MmochatUtil.msgbox(req.getHallState(), "您的交易账户中没有元宝!");
		}

		int num = 0;
		synchronized (me) {
			num = me.getAccount_bigmoney();
			if (num <= 0) {
				return MmochatUtil.msgbox(req.getHallState(), "您的交易账户中没有元宝!");
			}
			try {
				// 扣除交易账户中的元宝，增加角色元宝，限制元宝数量
				MmochatDao.getBigMoneyFromDealAccount(num, me.getRoleId());
			} catch (Exception e) {
				e.printStackTrace();
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}
			me.addAccount_bigmoney(-1 * num);
			me.addBig_money(num);
		}
		sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);

		return MmochatUtil.msgbox(req.getHallState(), "您取出了"
				+ MmochatUtil.wrapColor(num + "元宝!", Color.yellow)
				+ MmochatUtil.wrapColor("元宝交易平台求购的元宝，无法在此平台再次寄售。", Color.red)
				+ "您当前共有" + me.getBig_money() + "元宝，其中有"
				+ me.getLimit_bigmoney() + "元宝限制寄售。");
	}

	// 18.7 取回金钱
	@SkymobiService
	public SkymobiProtocolMessage handleC_18_7(SkymobiHandler handler,
			Mmochat_18_7C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		if (me.getAccount_smallmoney() <= 0) {
			return MmochatUtil.msgbox(req.getHallState(), "您的交易账户中没有金钱!");
		}

		int num = 0;
		synchronized (me) {
			num = me.getAccount_smallmoney();
			if ((long) Integer.MAX_VALUE - me.getSmall_money() < num) {
				return MmochatUtil.msgbox(req.getHallState(),
						"您包裹中携带的金钱过多，取回金钱后将超过金钱上限!请先转移部分金钱再取出账户金钱，以免金钱掉落!");
			}
			if (num <= 0) {
				return MmochatUtil.msgbox(req.getHallState(), "您的交易账户中没有金钱!");
			}
			try {
				// 扣除交易账户中的金钱，增加角色金钱
				MmochatDao.getSmallMoneyFromDealAccount(num, me.getRoleId());
			} catch (Exception e) {
				e.printStackTrace();
				if (MmochatConstant.testErrorRoleId) {
					log.error("roleId=" + me.getRoleId() + ",num=" + num);
				}
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}
			me.addAccount_smallmoney(-1 * num);
			me.addAndUpdateSmall_money(num);
		}
		sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
		return MmochatUtil.msgbox(req.getHallState(), MmochatUtil
				.getColorMoney(num)
				+ "文钱已经取出放入您的包裹,您可以按3键打开包裹查看余额!");
	}

	// 18.8 撤消订单
	@SkymobiService
	public SkymobiProtocolMessage handleC_18_8(SkymobiHandler handler,
			Mmochat_18_8C req) {
		MmochatPlayer me = MmochatMainService.getPlayerByRoleId(req, req
				.getRoleId());
		if (me == null) {
			return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
		}
		MmochatBigMoneyDeal deal = dealMap.get(req.getOrderId());
		if (deal == null || deal.getState() == MmochatBigMoneyDealState.交易结束) {
			sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
			return MmochatUtil.msgbox(req.getHallState(), "此订单已经交易完成或过期!");
		}
		String info = "";
		synchronized (deal) {
			if (deal.getState() == MmochatBigMoneyDealState.交易结束) {
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "此订单已经交易完成或过期!");
			}
			deal.setState(MmochatBigMoneyDealState.交易结束);
			List<MmochatBigMoneyDeal> dealList = new ArrayList<MmochatBigMoneyDeal>();
			dealList.add(deal);
			try {
				MmochatDao.batchUpdateAfterBigMoneyDealTimeOut(dealList);
			} catch (Exception e) {
				e.printStackTrace();
				deal.setState(MmochatBigMoneyDealState.交易中);
				sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
				return MmochatUtil.msgbox(req.getHallState(), "服务器忙,请稍候再试!");
			}
			dealMap.remove(deal.getId());
			if (deal.getType() == MmochatBigMoneyDealType.寄售) {
				// 归还剩余元宝
				me.addAccount_bigmoney(deal.getRest());
				info += "订单撤消成功。订单中未成交的" + deal.getRest() + "元宝已经转入"
						+ MmochatUtil.wrapColor("元宝交易-我的账户", Color.yellow)
						+ "，请及时取出元宝";
			} else if (deal.getType() == MmochatBigMoneyDealType.求购) {
				// 归还剩余金钱
				int money = deal.getRest() * deal.getPrice() * 100;
				me.addAccount_smallmoney(money);
				info += "订单撤消成功。订单中剩余的" + MmochatUtil.getColorMoney(money)
						+ "文钱已经转入"
						+ MmochatUtil.wrapColor("元宝交易-我的账户", Color.yellow)
						+ "，请及时取出金钱";
			}
		}

		sendBigMoneyDealWnd2Person(me, req.getHallState(), 0, 0);
		return MmochatUtil.msgbox(req.getHallState(), info);
	}
}
